package com.cloud.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cloud.admin.common.constant.UserConstants;
import com.cloud.admin.common.core.domain.AjaxResult;
import com.cloud.admin.common.core.page.TableDataInfo;
import com.cloud.admin.common.utils.StringUtils;
import com.cloud.admin.model.entity.SysUser;
import com.cloud.admin.service.SysPostService;
import com.cloud.admin.service.SysRoleService;
import com.cloud.admin.service.SysUserService;
import com.cloud.admin.shiro.security.ShiroUtils;
import com.cloud.admin.shiro.service.PasswordService;
import lombok.AllArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.Date;
import java.util.stream.Collectors;

/**
 * Created on 2019/7/25.
 *
 * @author douhaichao
 */
@RestController
@AllArgsConstructor
@RequestMapping("system/user")
public class UserController extends BaseController {

    private final String prefix = "system/user/";

    private final SysUserService userService;

    private final SysRoleService roleService;

    private final SysPostService postService;

    private final PasswordService passwordService;

    @RequiresPermissions("system:user:view")
    @GetMapping()
    public ModelAndView user() {
        ModelAndView view = super.baseView("user", prefix + "user");
        return view;
    }

    @RequiresPermissions("system:user:list")
    @PostMapping("list")
    public TableDataInfo list(SysUser user, Page page) {
        IPage pageData = userService.selectPageInfo(page, user);
        return getDataTable(pageData);
    }

    /**
     * 新增用户
     */
    @GetMapping("add")
    public ModelAndView add() {
        ModelAndView view = super.baseView("add", prefix + "add");
        view.addObject("roles", roleService.selectAll(null));
        view.addObject("posts", postService.selectAll(null));
        return view;
    }

    /**
     * 新增保存用户
     */
    @RequiresPermissions("system:user:add")
    @PostMapping("add")
    public AjaxResult addSave(@Validated SysUser user) {
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName()))) {
            return error("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
        } else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return error("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
        } else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return error("新增用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        user.setAvatar(config.getInitAvatar());
        user.setCreateBy(ShiroUtils.getLoginName());
        user.setCreateTime(new Date());
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @GetMapping("edit/{userId}")
    public ModelAndView edit(@PathVariable("userId") Long userId) {
        ModelAndView view = super.baseView("edit", prefix + "edit");
        view.addObject("user", userService.selectUserById(userId));
        view.addObject("roles", roleService.selectRolesByUserId(userId));
        view.addObject("posts", postService.selectPostsByUserId(userId));
        return view;
    }

    /**
     * 修改保存用户
     */
    @RequiresPermissions("system:user:edit")
    @PostMapping("edit")
    public AjaxResult editSave(@Validated SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && SysUser.isAdmin(user.getUserId())) {
            return error("不允许修改超级管理员用户");
        } else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return error("修改用户'" + user.getLoginName() + "'失败，手机号码已存在");
        } else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return error("修改用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(ShiroUtils.getLoginName());
        user.setUpdateTime(new Date());
        return toAjax(userService.updateUser(user));
    }

    @RequiresPermissions("system:user:resetPwd")
    @GetMapping("resetPwd/{userId}")
    public ModelAndView resetPwd(@PathVariable("userId") Long userId) {
        ModelAndView view = super.baseView("resetPwd", prefix + "resetPwd");
        view.addObject("user", userService.getById(userId));
        return view;
    }

    @RequiresPermissions("system:user:resetPwd")
    @PostMapping("resetPwd")
    public AjaxResult resetPwdSave(SysUser user) {
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        if (userService.updateById(user)) {
            if (ShiroUtils.getUserId() .equals( user.getUserId())) {
                // 这里的对象要把SysUser改成User对象
//                ShiroUtils.setSysUser(userService.getById(user.getUserId()));
            }
            return success();
        }
        return error();
    }

    @RequiresPermissions("system:user:remove")
    @PostMapping("remove")
    public AjaxResult remove(String ids) {
        try {
            return toAjax(userService.removeByIds(Arrays.stream(ids.split(",")).collect(Collectors.toList())));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 校验用户名
     */
    @PostMapping("checkLoginNameUnique")
    public String checkLoginNameUnique(SysUser user) {
        return userService.checkLoginNameUnique(user.getLoginName());
    }

    /**
     * 校验手机号码
     */
    @PostMapping("checkPhoneUnique")
    public String checkPhoneUnique(SysUser user) {
        return userService.checkPhoneUnique(user);
    }

    /**
     * 校验email邮箱
     */
    @PostMapping("checkEmailUnique")
    public String checkEmailUnique(SysUser user) {
        return userService.checkEmailUnique(user);
    }

    /**
     * 用户状态修改
     */
    @RequiresPermissions("system:user:edit")
    @PostMapping("changeStatus")
    public AjaxResult changeStatus(SysUser user) {
        return toAjax(userService.changeStatus(user));
    }
}
